package com.qf;

import com.qf.mapper.EmpMapper;
import com.qf.pojo.Emp;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.InputStream;
import java.util.List;

/**
 * 单元测试
 * @author lixu
 */
public class MybatisTest {
    /**
     * 查询
     *         //  一个工厂 可以生产很多双鞋
     *         //鞋连接Mysql 并查询数据
     */
    @Test
    public void mybatisFind() throws Exception{
        //1:Mybatis使用的 23种设计模式中 工厂模式
        //1.1材料
        String resource = "mybatis-config.xml";
        //1.2 将上面的文件成流
        InputStream resourceAsStream = Resources.getResourceAsStream(resource);
        //1.3:构建工厂对象
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder =
                new SqlSessionFactoryBuilder();
        //2：工厂对象
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(resourceAsStream);

        //3:SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //4: ORM框架  自动映射   Java代码与SQL语句分离
        List<Emp> empList = sqlSession.selectList("emp.findAll");//硬编码问题

        for (Emp emp : empList) {
            System.out.println(emp);
        }
        // 约定大于配置
    }

    /**
     * 查询  带有接口的Mapper文件的查询
     */
    @Test
    public void mybatisFindInterface() throws Exception{
        //1:Mybatis使用的 23种设计模式中 工厂模式
        //1.1材料
        String resource = "mybatis-config.xml";
        //1.2 将上面的文件成流
        InputStream resourceAsStream = Resources.getResourceAsStream(resource);
        //1.3:构建工厂对象
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder =
                new SqlSessionFactoryBuilder();
        //2：工厂对象
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(resourceAsStream);

        //3:SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //4: 接口
        EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);
        List<Emp> empList = empMapper.findAll("王嚎嚎");

        empList.stream().forEach(System.out::println);

    }

}
